import React from 'react';
import { Form, Input, Radio, Select, DatePicker, Row, Col, InputNumber } from 'antd';
import CascaderLoad from '@/components/CascaderLoad';
import { dictionaryList } from '@/services/dictionary';
import moment from 'moment';

const { Option } = Select;
const { RangePicker, MonthPicker } = DatePicker;

const FormItem = props => {
    const {
        type = 'input',
        label = '',
        prop: receivedProp = [], // prop可以传一个值也可以是一个数组
        initialValue: receivedInitialValue = [], // initialValue可以传一个值，也可以传一个数组
        initialFormInfo = {}, // 可以把所有初始值放在initialFormInfo
        required = false,
        dictCode,
        options = [],
        disabled = false,
        dict = {},
        precision = 1,
        initialSecondOptions = [],
        onChange,
        rules,
        form
    } = props;
    const {
        companyId,
        healthyState: receivedHealthyState = '',
        notesSource: receivedNotesSource = ''
    } = initialFormInfo;

    const prop = Array.isArray(receivedProp) ? receivedProp : new Array(receivedProp);
    const initialValue = Array.isArray(receivedInitialValue) ? receivedInitialValue : new Array(receivedInitialValue);
    const { getFieldDecorator } = form;
    // 101厦门1005深圳
    const returnDefinedAreaCode = () => (companyId === 101 || companyId === 1005 ? '86' : '65');
    const returnAreaCode = areaCode => {
        if (areaCode === '' || areaCode === undefined) {
            return returnDefinedAreaCode();
        }
        return areaCode;
    };
    const [secondHouseholdTypeOptions, setSecondHouseholdTypeOptions] = React.useState();
    const [healthyState, setHealthyState] = React.useState(receivedHealthyState);
    const [notesSource, setNotesSource] = React.useState('');
    const list = ['other', 'internal_recommendation', 'forum'];
    const onHealthStateChange = e => {
        if (e.target.value !== 'other') {
            form.setFieldsValue({ healthyStateDesc: '' });
        }
        setHealthyState(e.target.value);
    };
    const onNotesSourceChange = val => {
        console.log(val);
        if (!list.includes(val)) {
            form.setFieldsValue({ notesSourceDetail: '' });
        }
        setNotesSource(val);
    };
    const onHouseholdTypeChange = async (_, { props: { id } }) => {
        form.setFieldsValue({ secondHouseholdType: undefined });
        const { code, data } = await dictionaryList({ parentId: id });
        if (code === 10000) {
            setSecondHouseholdTypeOptions(data);
        }
    };
    React.useEffect(() => {
        setHealthyState(receivedHealthyState);
    }, [receivedHealthyState]);
    React.useEffect(() => {
        setNotesSource(receivedNotesSource);
    }, [receivedNotesSource]);
    if (type === 'address') {
        return (
            <Form.Item label={label} required={required}>
                <Row>
                    <Col>
                        <Form.Item style={{ marginBottom: 8 }}>
                            {getFieldDecorator(prop[0], {
                                initialValue:
                                    (initialValue[0] && initialValue[0].split(',')) ||
                                    (initialFormInfo[prop[0]] && initialFormInfo[prop[0]].split(',')) ||
                                    [],
                                rules: [
                                    {
                                        required,
                                        message: `请选择${label}`
                                    }
                                ]
                            })(
                                <CascaderLoad
                                    disabled={disabled}
                                    cascaderProps={{
                                        placeholder: `请选择${label}`
                                    }}
                                    // asianData={asian}
                                />
                            )}
                        </Form.Item>
                    </Col>
                    <Col>
                        <Form.Item style={{ marginBottom: 0 }}>
                            {getFieldDecorator(prop[1], {
                                initialValue: initialValue[1] || initialFormInfo[prop[1]],
                                rules: [
                                    {
                                        required,
                                        message: `请输入详细${label}`
                                    },
                                    {
                                        min: 1,
                                        max: 50,
                                        message: '请输入1~50个字符'
                                    },
                                    {
                                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                        message: '此处不能输入空格'
                                    }
                                ]
                            })(
                                <Input.TextArea
                                    disabled={disabled}
                                    rows={4}
                                    style={{ height: 100 }}
                                    placeholder={`请输入详细${label}`}
                                />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
            </Form.Item>
        );
    }
    if (type === 'healthyState') {
        return (
            <Form.Item label={label} style={{ marginBottom: 0 }}>
                <Row>
                    <Col span={12}>
                        <Form.Item>
                            {getFieldDecorator(prop[0], {
                                initialValue: initialValue[0] || initialFormInfo[prop[0]],
                                rules: [
                                    {
                                        required,
                                        message: '性别不能为空'
                                    }
                                ]
                            })(
                                <Radio.Group disabled={disabled} onChange={onHealthStateChange}>
                                    {dict.healthyState &&
                                        dict.healthyState.map(item => (
                                            <Radio value={item.dictValue} key={item.dictValue}>
                                                {item.dictName}
                                            </Radio>
                                        ))}
                                </Radio.Group>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            style={{
                                marginBottom: 0,
                                paddingBottom: 0,
                                display: healthyState === 'other' ? 'block' : 'none'
                            }}
                        >
                            {getFieldDecorator(prop[1], {
                                initialValue: initialValue[1] || initialFormInfo.healthyStateDesc || '',
                                rules: [
                                    {
                                        required,
                                        message: `请描述${label}`
                                    },
                                    {
                                        min: 1,
                                        max: 50,
                                        message: '请输入1~50个字符'
                                    },
                                    {
                                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                        message: '此处不能输入空格'
                                    }
                                ]
                            })(<Input disabled={disabled} placeholder={`请描述${label}`} />)}
                        </Form.Item>
                    </Col>
                </Row>
            </Form.Item>
        );
    }
    if (type === 'select') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue: initialValue[0] || initialFormInfo[prop[0]] || undefined,
                    rules: [
                        {
                            required,
                            message: `请选择${label}`
                        }
                    ]
                })(
                    <Select disabled={disabled} placeholder={`请选择${label}`} allowClear>
                        {dict[dictCode] &&
                            dict[dictCode].map(item => (
                                <Option value={item.dictValue} key={item.dictValue}>
                                    {item.dictName}
                                </Option>
                            ))}
                    </Select>
                )}
            </Form.Item>
        );
    }
    if (type === 'notesSource') {
        return (
            <Form.Item label={label} required={required}>
                <Row>
                    <Col>
                        <Form.Item style={{ marginBottom: 8 }}>
                            {getFieldDecorator(prop[0], {
                                initialValue: initialValue[0] || initialFormInfo[prop[0]] || undefined,
                                rules: [
                                    {
                                        required,
                                        message: `请选择${label}`
                                    }
                                ]
                            })(
                                <Select
                                    disabled={disabled}
                                    onChange={onNotesSourceChange}
                                    placeholder={`请选择${label}`}
                                    allowClear
                                >
                                    {dict[dictCode] &&
                                        dict[dictCode].map(item => (
                                            <Option value={item.dictValue} key={item.dictValue}>
                                                {item.dictName}
                                            </Option>
                                        ))}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                    <Col>
                        <Form.Item
                            style={{
                                marginBottom: 0,
                                display: list.includes(notesSource) ? 'block' : 'none'
                            }}
                        >
                            {getFieldDecorator(prop[1], {
                                initialValue: initialValue[1] || initialFormInfo[prop[1]],
                                rules: [
                                    {
                                        required: list.includes(notesSource),
                                        message: `请输入详细${label}`
                                    },
                                    {
                                        min: 1,
                                        max: 50,
                                        message: '请输入1~50个字符'
                                    },
                                    {
                                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                        message: '此处不能输入空格'
                                    }
                                ]
                            })(<Input.TextArea disabled={disabled} rows={5} placeholder={`请输入详细${label}`} />)}
                        </Form.Item>
                    </Col>
                </Row>
            </Form.Item>
        );
    }
    if (type === 'householdType') {
        return (
            <Form.Item label={label} style={{ marginBottom: 0 }} required={required}>
                <Row gutter={15}>
                    <Col md={12} xs={24} sm={24}>
                        <Form.Item>
                            {getFieldDecorator(prop[0], {
                                initialValue: initialValue[0] || initialFormInfo[prop[0]] || undefined,
                                rules: [
                                    {
                                        required,
                                        message: '请选择户籍'
                                    }
                                ]
                            })(
                                <Select
                                    disabled={disabled}
                                    allowClear
                                    placeholder="请选择"
                                    onChange={onHouseholdTypeChange}
                                >
                                    {dict[dictCode] &&
                                        dict[dictCode].map(item => (
                                            <Option value={item.dictValue} key={item.dictValue} id={item.id}>
                                                {item.dictName}
                                            </Option>
                                        ))}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={12} xs={24} sm={24}>
                        <Form.Item>
                            {getFieldDecorator(prop[1], {
                                initialValue: initialValue[1] || initialFormInfo[prop[1]] || undefined,
                                rules: [
                                    {
                                        required,
                                        message: '请选择'
                                    }
                                ]
                            })(
                                <Select disabled={disabled} allowClear placeholder="请选择">
                                    {!secondHouseholdTypeOptions &&
                                        initialSecondOptions.map(item => (
                                            <Option value={item.dictValue} key={item.dictValue}>
                                                {item.dictName}
                                            </Option>
                                        ))}
                                    {secondHouseholdTypeOptions &&
                                        secondHouseholdTypeOptions.map(item => (
                                            <Option value={item.dictValue} key={item.dictValue}>
                                                {item.dictName}
                                            </Option>
                                        ))}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
            </Form.Item>
        );
    }
    if (type === 'nationalArea') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue:
                        (initialValue[0] && initialValue[0].split(',')) ||
                        (initialFormInfo[prop[0]] && initialFormInfo[prop[0]].split(',')) ||
                        [],
                    rules: [
                        {
                            required,
                            message: `请选择${label}`
                        }
                    ]
                })(
                    <CascaderLoad
                        disabled={disabled}
                        cascaderProps={{
                            placeholder: '请选择籍贯/国籍'
                        }}
                        // asianData={asian}
                    />
                )}
            </Form.Item>
        );
    }
    if (type === 'date') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue:
                        (initialValue[0] && moment(initialValue[0])) ||
                        (initialFormInfo[prop[0]] && moment(initialFormInfo[prop[0]])) ||
                        undefined,
                    rules: [
                        {
                            required,
                            message: `请选择${label}`
                        }
                    ]
                })(<DatePicker disabled={disabled} style={{ width: '100%' }} placeholder={`请选择${label}`} />)}
            </Form.Item>
        );
    }
    if (type === 'month') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue:
                        (initialValue[0] && moment(initialValue[0])) ||
                        (initialFormInfo[prop[0]] && moment(initialFormInfo[prop[0]])) ||
                        undefined,
                    rules: [
                        {
                            required,
                            message: `请选择${label}`
                        }
                    ]
                })(<MonthPicker disabled={disabled} style={{ width: '100%' }} placeholder={`请选择${label}`} />)}
            </Form.Item>
        );
    }
    if (type === 'dateRange') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue:
                        (initialValue[0] && [moment(initialValue[0]), moment(initialValue[1])]) ||
                        (initialFormInfo[prop[0]] && [
                            moment(initialFormInfo[prop[0]]),
                            moment(initialFormInfo[prop[1]])
                        ]) ||
                        [],
                    rules: [
                        {
                            required,
                            message: `请选择${label}`
                        }
                    ]
                })(
                    <RangePicker
                        mode={['month', 'month']}
                        format="YYYY-MM"
                        onPanelChange={val =>
                            form.setFieldsValue({
                                [prop[0]]: val
                            })
                        }
                        disabled={disabled}
                    />
                )}
            </Form.Item>
        );
    }
    if (type === 'idCard') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue: initialValue[0] || initialFormInfo[prop[0]],
                    rules: [
                        {
                            required,
                            message: `请输入${label}`
                        },
                        {
                            max: 20,
                            min: 2,
                            message: '请输入2~20位字符'
                        },
                        {
                            pattern: /^[^\s]+(\s+[^\s]+)*$/,
                            message: '此处不能输入空格'
                        }
                    ]
                })(<Input disabled={disabled} onChange={onChange} placeholder={`请输入${label}`} />)}
            </Form.Item>
        );
    }
    if (type === 'mail') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue: initialValue[0] || initialFormInfo[prop[0]],
                    rules: [
                        {
                            required,
                            message: `请输入${label}`
                        },
                        {
                            pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
                            message: '邮件格式不正确'
                        }
                    ]
                })(<Input disabled={disabled} placeholder={`请输入${label}`} allowClear />)}
            </Form.Item>
        );
    }
    if (type === 'telephone') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[1], {
                    initialValue: initialValue[1] || initialFormInfo[prop[1]],
                    rules: [
                        {
                            required,
                            validator(rule, value, callback) {
                                const regex = /^\d{7,11}$/;
                                if (required && !value) {
                                    callback('手机号码不能为空');
                                } else if (value && !regex.test(value)) {
                                    callback('只能输入7-11位数字');
                                }
                                callback();
                            }
                        }
                    ]
                })(
                    <Input
                        disabled={disabled}
                        placeholder={`请填入${label}`}
                        addonBefore={getFieldDecorator(prop[0], {
                            initialValue: initialValue[0] || returnAreaCode(initialFormInfo[prop[0]])
                        })(
                            <Select disabled={disabled} placeholder="请选择区号" place style={{ width: 70 }}>
                                <Option value="86">+86</Option>
                                <Option value="65">+65</Option>
                            </Select>
                        )}
                    />
                )}
            </Form.Item>
        );
    }
    if (type === 'radio') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue: initialValue[0] || initialFormInfo[prop[0]],
                    rules: [
                        {
                            required,
                            message: `${label}不能为空`
                        }
                    ]
                })(
                    <Radio.Group disabled={disabled}>
                        {dict[dictCode] &&
                            dict[dictCode].map(item => (
                                <Radio value={item.dictValue} key={item.dictValue}>
                                    {item.dictName}
                                </Radio>
                            ))}
                        {options.length > 0 &&
                            options.map(item => (
                                <Radio value={item.dictValue} key={item.dictValue}>
                                    {item.dictName}
                                </Radio>
                            ))}
                    </Radio.Group>
                )}
            </Form.Item>
        );
    }
    if (type === 'textArea') {
        return (
            <Form.Item help="2-400个字符" label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue: initialValue[0] || initialFormInfo[prop[0]],
                    rules: [
                        {
                            required,
                            message: `请输入${label}`
                        },
                        {
                            min: 2,
                            max: 400,
                            message: '请输入2~400个字符'
                        }
                    ]
                })(<Input.TextArea disabled={disabled} rows={4} />)}
            </Form.Item>
        );
    }
    if (type === 'inputNumber') {
        return (
            <Form.Item label={label}>
                {getFieldDecorator(prop[0], {
                    initialValue: initialValue[0] || initialFormInfo[prop[0]],
                    rules: [
                        {
                            required,
                            message: `请输入${label}`
                        }
                    ]
                })(
                    <InputNumber
                        style={{ width: '100%' }}
                        precision={precision}
                        placeholder={`请输入${label}`}
                        disabled={disabled}
                        allowClear
                    />
                )}
            </Form.Item>
        );
    }
    return (
        <Form.Item label={label}>
            {getFieldDecorator(prop[0], {
                initialValue: initialValue[0] || initialFormInfo[prop[0]],
                rules: rules || [
                    {
                        required,
                        message: `请输入${label}`
                    },
                    {
                        min: 1,
                        max: 50,
                        message: '请输入1~50个字符'
                    },
                    {
                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                        message: '此处不能输入空格'
                    }
                ]
            })(<Input disabled={disabled} placeholder={`请输入${label}`} allowClear />)}
        </Form.Item>
    );
};

export default FormItem;
